package com.fly.simple;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import com.fly.simple.entity.Article;
import com.fly.simple.entity.BlogData;
import com.fly.simple.entity.Record;
import com.fly.simple.utils.JsonBeanUtils;
import com.fly.simple.utils.ShellExecutor;

import lombok.extern.slf4j.Slf4j;

/**
 * pom-print.xml中使用slf4j-simple规避log4j-slf4j-impl将日志打印到console<br>
 * slf4j-simple默认情況下只输出info以上（包含info）级別的日志
 * 
 */
@Slf4j
public class JsonDataPrint
{
    /**
     * 验证: syso输出内容，jar运行可写入文件<br>
     * 打包：mvn clean package -f pom-print.xml <br>
     * 运行：java -jar files-listener-0.0.1.jar > /work/1.txt
     * 
     * @param args
     * @throws IOException
     */
    public static void main(String[] args)
        throws IOException
    {
        // windows下Jar运行返回值中文乱码，unix下Jar运行返回值正常
        List<Article> articles = IntStream.rangeClosed(1, 2)
            .mapToObj(i -> String.format("curl -e \"blog.csdn.net\" \"https://blog.csdn.net/community/home-api/v1/get-business-list?page=%s&size=100&businessType=blog&username=qq_16127313\"", i))
            .map(cmd -> ShellExecutor.execute(cmd))
            .map(json -> parseToArticles(json))
            .flatMap(List::stream)
            .collect(Collectors.toList());
        
        // 构造对象
        BlogData blogData = new BlogData().setData(new Record().setList(articles));
        String jsonData = JsonBeanUtils.beanToJson(blogData, true);
        System.out.println(jsonData);
    }
    
    /**
     * 解析json为List
     * 
     * @param json
     * @return
     */
    private static List<Article> parseToArticles(String json)
    {
        try
        {
            return JsonBeanUtils.jsonToBean(json, BlogData.class, true).getData().getList();
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
            return Collections.emptyList();
        }
    }
}
